<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="list">
        <div class="good">
            <div class="name"></div>
        </div>
    </div>
    <div class="list">
        <div class="good">
            <div class="name"></div>
        </div>
    </div>
    <div class="list">
        <div class="good">
            <div class="name"></div>
        </div>
    </div>
</body>

</html>
<script>
    //商品列表数据
    var goodlist = [
        { id: 1, name: 'iphone' },
        { id: 2, name: 'iphone x' },
        { id: 3, name: 'iphone se' },
    ]
    //购物车数据
    var oo = { list: [] }

    //渲染商品列表
    function render() {
        var list = document.querySelector('.list');
        list.innerHTML = goodlist.map((item) => {
            return `<div class="good">
                        <div class="name">${item.name}</div>
                        <button>加入购物车</button>
                    </div>`
        }).join('')
    }

    function renderGouwuche() {
        var gouwuche = document.querySelector('.gouwuche');
        gouwuche.innerHTML = oo.list.map((item) => {
            return `<div class="good">
                        <div class="name">${item.name}</div>
                    </div>`
        }).join('')
    }

    render();


    //给list绑定点击事件
    var list = document.querySelector('.list');
    list.onclick = function (e) {
        if (e.target.tagName == 'BUTTON') {
            //获取点击商品的下标
            var btns = [...document.querySelectorAll('button')]
            var index = btns.findIndex((item) => {
                return item == e.target;
            })

            //添加商品数据到 购物车数组
            oo.list.push(goodlist[index]);
            //ooo.list = [ goodlist[index] ]
            //重新渲染购物车列表
            renderGouwuche();
        }
    }

    var ooo = new Proxy(oo, {
        set: (a, b, c) => {
            console.log('set');
            renderGouwuche();
        },
        get: (a, b, c) => { console.log('获取了oo对象', a, b, c) }
    })

</script>